package risk.control.project.framework;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import risk.control.project.config.constant.ServiceName;
import risk.control.project.framework.base.BaseEncryption;
import risk.control.project.framework.service.BaseHandleService;
import risk.control.project.framework.service.SessionService;
import risk.control.project.framework.service.TimestampService;
import risk.control.project.framework.service.TokenService;
import risk.control.project.utils.response.ResponseCode;

import java.util.HashMap;

/**
 * 处理请求的基类
 */
public abstract class PostController extends BaseEncryption {
    private static final Logger logger = LoggerFactory.getLogger(PostController.class);

    //子类具体实现
    protected abstract String postRequest(HashMap<String, String> requestParam);

    @Autowired
    public BaseHandleService baseHandleService; //处理基础请求

    @Autowired
    public SessionService sessionService; //session

    @Autowired
    public TokenService tokenService; //token

    @Autowired
    public TimestampService timestampService; //timestamp

    protected String handleRequest(HttpServletRequest req) {
        //获取原始请求信息
        HashMap<String, String> requestParamMap = baseHandleService.getRequestInfo(req);
        String serveName = requestParamMap.get("serveName");
        //校验serveName的合法性
        HashMap<String, String> serveNameHashMap = baseHandleService.verifierServiceName(serveName);
        if (!serveNameHashMap.get("state").equals("000")) {
            return generateFail(serveNameHashMap.get("msg"));
        }
        //判断api类型
        String type = ServiceName.Map.get(serveName);
        return switch (type) {
            case "-1" -> generateFail("该api已停止请求");
            case "0" -> handleRequest(false, requestParamMap);
            case "1" -> handleRequest(true, requestParamMap);
            case "2" -> postRequest(requestParamMap);
            default -> generateFail("错误的api请求");
        };
    }


    /**
     * 预处理请求
     *
     * @param needToken       是否需要验证token
     * @param requestParamMap 请求信息
     * @return resp
     */
    private String handleRequest(boolean needToken, HashMap<String, String> requestParamMap) {
        String sessionId = requestParamMap.get("sessionId");
        String requestBody = requestParamMap.get("requestBody");
        //每个请求校验session的合法性
        HashMap<String, String> sessionMap = sessionService.verifier(sessionId);
        if (!sessionMap.get("state").equals("000")) {
            return generateFailForCode(ResponseCode.SESSION_ERROR, sessionMap.get("msg"));
        }
        String realBody = baseHandleService.decryptRequestBody(requestBody);
        requestParamMap.put("requestBody", realBody);//解密body
        //每个请求校验时间戳的合法性
        HashMap<String, String> timestamp = timestampService.verifierTimestamp(realBody);
        if (!timestamp.get("state").equals("000")) {
            return generateFail(timestamp.get("msg"));
        }
        //需要校验token的合法性
        if (needToken) {
            HashMap<String, String> tokenVerifier = tokenService.verifier(realBody);
            if (!tokenVerifier.get("state").equals("000")) {
                return generateFailForCode(ResponseCode.TOKEN_ERROR, tokenVerifier.get("msg"));
            }
        }
        return postRequest(requestParamMap);//返回子类处理
    }

    protected String generateSessionId() {
        return sessionService.generateSessionId();
    }

    protected String generateToken(String userId) {
        return tokenService.generateToken(userId);
    }
}
